<?php

namespace Home\Controller;

use Think\Controller;

class IndexController extends Controller {

    // 用户注册
    public function UserReg() {
        $User = D("User");
        $res = [];
        // 1.0 获取用户名
        $UserName = I("post.UserName");
        // 2.0 构建查询条件
        $condition['UserName'] = $UserName;
        // 3.0 判断用户名是否存在
        $isRepeat = $User->where($condition)->select();
        if ($isRepeat) {
            // 输出用户名已存在
            $res = [
                "statu" => -1
            ];
        } else {
            // 4.0 获取所有的Post数据
            $data = I('post.');
            // 5.0 密码MD5加密
            $data["UserPassword"] = strtolower(md5(I("post.UserPassword")));
            $data["CreateUserID"] = 0;
            $data["OtherID"] = "";
            if ($User->create($data)) {
                $newID = $User->add();
                // 7.0  注册成功
                if ($newID) {
                    // 8.0 初始化融云对象
                    $rongCloud = new \Org\Util\ServerAPI('0vnjpoadnw9xz', 'IDNF6hMI3bMFT');
                    $rongres = $rongCloud->getToken($newID, $UserName, I("post.UserPhoto"));
                    // 将字符串转换为对象
                    $rongarr = json_decode($rongres, true);
                    // 更新token
                    $User->where('UserID=' . $newID)->setField('Token', $rongarr["token"]);
                    $res = [
                        "statu" => 1,
                        "userinfo" => $User->find($newID)
                    ];
                } else {
                    $res = [
                        "statu" => 0
                    ];
                }
            }
        }
        // 输出字符串
        $this->ajaxReturn($res, "json");
    }

    // 用户登录
    public function UserLogin() {
        $User = M("User");
        $res = [];
        // 获取用户名和密码
        $UserName = I("post.UserName");
        $UserPwd = I("post.UserPwd");

        $condition['UserName'] = $UserName;
        // 查询用户名是否存在
        $IsInDb = $User->where($condition)->select();
        if ($IsInDb) {
            // md5密码加密
            $condition['UserPwd'] = strtolower(md5($UserPwd));
            // 查询用户名和密码是否正确
            $result = $User->where($condition)->select();
            if ($result) {
                // 登录成功
                $res = [
                    "statu" => 1,
                    "userinfo" => $result[0]
                ];
            } else {
                // 密码错误
                $res = [
                    "statu" => 0
                ];
            }
        } else {
            // 用户名不存在
            $res = [
                "statu" => -1
            ];
        }
        $this->ajaxReturn($res, "json");
    }

    // 获取用户集合信息
    public function GetUsersInfo($ids) {
        $User = M("User");
        $map['UserID'] = array('in', $ids);
        $res = $User->where($map)->select();
        $this->ajaxReturn($res, "json");
    }

    // 获取单个用户信息
    public function GetUserByID($uid) {
        $User = M("User");
        $res = $User->find($uid);
        $this->ajaxReturn($res, "json");
    }

    // 获取所有非我好友的用户
    public function getUserByPage($uid, $page) {
        $User = D("User");
        $offset = ($page - 1) * 20;
        $res = $User->query("SELECT * from apicloud_im_user where userid!=$uid and  ConversationType = 'PRIVATE' and UserID not in(select userrelativeid from apicloud_im_userrelative where userid=$uid) order by regtime desc limit $offset,20");
        $this->ajaxReturn($res, "json");
    }

    // 分页获取所有类型数据
    public function getGroupByPage($page, $conversationtype = "GROUP") {
        $where = I("post.where");
        if (!$where) {
            $where = " 1=1 ";
        }
        $User = D("User");
        $offset = ($page - 1) * 20;
        $res = $User->query("SELECT * from apicloud_im_user where ConversationType='$conversationtype' and $where order by regtime desc limit $offset,20");
        $this->ajaxReturn($res, "json");
    }

    // 获取我所有的好友，群，聊天室等
    public function getAllMyRelative($userid) {
        $User = D("User");
        $res = $User->query("select * from apicloud_im_user where UserID in (select b.UserRelativeID from apicloud_im_user a left JOIN apicloud_im_userrelative b on a.UserID=b.UserID where a.UserID=$userid)");
        $this->ajaxReturn($res, "json");
    }

    // 添加关系
    public function addUser($userid, $relativeuserid) {
        $User = D("User");
        $relatveObj = $User->find($relativeuserid);

        // 添加关系
        $UserRelative = D('Userrelative');
        $UserRelative->UserID = $userid;
        $UserRelative->UserRelativeID = $relativeuserid;
        $UserRelative->ConversationType = $relatveObj["conversationtype"];
        $UserRelative->CreateTime = time();
        if ($UserRelative->add()) {
            $res = [
                "statu" => 1
            ];
        } else {
            $res = [
                "statu" => 0
            ];
        }
        $this->ajaxReturn($res, "json");
    }

    // 删除好友，或退出群，聊天室等等
    public function removeRelative($userid, $relativeuserid) {
        $Userrelative = D("Userrelative");
        $condition['UserID'] = $userid;
        $condition['UserRelativeID'] = $relativeuserid;
        // 查询用户名是否存在
        $IsInDb = $Userrelative->where($condition)->select();

        if ($IsInDb) {
            $obj = $IsInDb[0];
            if ($Userrelative->delete($obj["autoid"])) {
                // 删除成功
                $res = [
                    "statu" => 1
                ];
            } else {
                // 删除失败
                $res = [
                    "statu" => 0
                ];
            }
        } else {
            // 本身就不是好友关系
            $res = [
                "statu" => -2
            ];
        }

        $this->ajaxReturn($res, "json");
    }

// 创建群
    public function createGroup($userId) {

        $User = D('User');
        // 1.0 获取用户名
        $UserName = I("post.UserName");
        // 2.0 构建查询条件
        $condition['UserName'] = $UserName;
        // 3.0 判断用户名是否存在
        $isRepeat = $User->where($condition)->select();
        if ($isRepeat) {
            // 输出用户名已存在
            $res = [
                "statu" => -1
            ];
        } else {
            $User->ConversationType = 'GROUP';
            $User->UserName = I('post.UserName');
            $User->UserPhoto = I('post.UserPhoto');
            $User->UserPassword = "";
            $User->Token = "";
            $User->Regtime = time();
            $User->CreateUserID = $userId;
            $User->OtherID = "";
            $newID = $User->add();
            if ($newID) {
                $rongCloud = new \Org\Util\ServerAPI('0vnjpoadnw9xz', 'IDNF6hMI3bMFT');
                $rongRes = $rongCloud->groupCreate($userId, $newID, I('post.UserName'));
                if ($rongRes) {
                    // 添加关系
                    $UserRelative = D('Userrelative');
                    $UserRelative->UserID = $userId;
                    $UserRelative->UserRelativeID = $newID;
                    $UserRelative->ConversationType = 'GROUP';
                    $UserRelative->CreateTime = time();
                    if ($UserRelative->add()) {
                        // 创建成功并同步群
                        $rongCloud->groupSync($userId, ['' . $newID . '' => I('post.UserName')]);
                        $res = [
                            "statu" => 1,
                            "res" => $rongRes
                        ];
                    } else {
                        $User->delete($newID);
                        // 插入关系表错误
                        $res = [
                            "statu" => -3
                        ];
                    }
                } else {
                    $User->delete($newID);
                    // 融云创建失败
                    $res = [
                        "statu" => 0
                    ];
                }
            } else {
                // 参数错误
                $res = [
                    "statu" => -2
                ];
            }
        }

        $this->ajaxReturn($res, "json");
    }

// 上传图片
    public function uploads() {
        $res = [];
        $upload = new \Think\Upload(); // 实例化上传类
        $upload->maxSize = 3145728; // 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg'); // 设置附件上传类型
        $upload->rootPath = './Public/Uploads/'; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录
        // 采用GUID序列命名
        $upload->saveName = md5();
        // 上传文件 
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
            $res = [
                "statu" => 0
            ];
        } else {// 上传成功
            $res = [
                "statu" => 1,
                "path" => './Public/Uploads/' . $info["pic"]["savepath"] . $info["pic"]["savename"]
            ];
        }
        $this->ajaxReturn($res, "json");
    }

}
